package drds.plus.rule_engine.rule;

import drds.plus.rule_engine.rule.sharding_function.ShardingFunction;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

/**
 * 基于groovy实现
 */
@Slf4j
public class ShardingFunctionRule<T> extends EnumerativeExpressionRule<T> {


    private ShardingFunction shardingFunction;

    public ShardingFunctionRule(String expression) {
        this(expression, null);
    }

    public ShardingFunctionRule(String expression, String extraPackagesStr) {
        super(expression);

        if (expression == null) {
            throw new IllegalArgumentException("未指定 expression");
        }

        shardingFunction = new ShardingFunction() {

            public Object eval(Map map, Object outerCtx) {
                return null;
            }
        };
    }


    /**
     * 替换成(map.get("id"));以在运算时通过列名取得参数值（描点值）
     */
    protected String replace(RuleColumn ruleColumn) {
        return new StringBuilder("(map.get(\"").append(ruleColumn.columnName).append("\"))").toString();
    }

    /**
     * 调用groovy的方法：public Object eval(Map map,Map ctx){...}");
     */
    public T eval(Map<String, Object> columnValues, Object outerCtx) {
        T value = (T) shardingFunction.eval(columnValues, outerCtx);
        if (value == null) {
            throw new IllegalArgumentException("rule_engine eval resulte is null! rule_engine:" + this.expression);
        }
        return value;
    }

}
